<template>
  <van-field
    v-model="state.queryName"
    name="region"
    @click="openPicker"
    :disabled="isDisabled"
    label-align="top"
    right-icon="arrow-down"
    placeholder="选择区域"
  />

  <van-popup v-model:show="state.showPicker" destroy-on-close position="bottom">
    <van-picker
      :columns="state.region"
      :model-value="state.pickerValue"
      @confirm="onPicker"
      @cancel="state.showPicker = false"
    />
  </van-popup>
</template>

<script setup>
import { ref, computed, watch, onMounted, reactive } from "vue";
import { getDictDataApi } from "@/api/common";
import { getUserInfo } from "@/utils/userInfo.js";
const props = defineProps({
  modelValue: String,
});
const emit = defineEmits(["update:modelValue", "update:name"]);
const state = reactive({
  showPicker: false,
  region: [],
  queryName: "",
});
const userInfo = computed(() => getUserInfo());
const regionCode = computed(() => {
  return userInfo.value.countyCode;
});

const openPicker = () => {
  if (isDisabled.value) return;
  state.showPicker = true;
};

const onPicker = ({ selectedValues, selectedOptions }) => {
  emit("update:modelValue", selectedOptions[0].value);
  state.queryName = selectedOptions[0].text;
  state.showPicker = false;
};
const val = ref(props.modelValue);
const isDisabled = ref(false);

watch(
  () => props.modelValue,
  (newVal) => {
    if (!newVal) state.queryName = "";
  }
);

onMounted(() => {
  getDictDataApi("sys_areacode").then(({ data }) => {
    if (data && data.code === 200) {
      state.region = data.data.map((item) => {
        return {
          text: item.dictlabel,
          value: item.dictvalue,
        };
      });

      if (["500100", "5001", "500000"].includes(regionCode.value)) {
        isDisabled.value = false;
        val.value = "";
      } else {
        isDisabled.value = true;
        val.value = regionCode.value;
        state.queryName = state.region.find(
          (item) => item.value == regionCode.value
        ).text;
      }
    }
  });
});
</script>

<style lang="less" scoped>
.van-field {
  width: calc(100% - 40px);
  background: #fff;
  height: 100%;
  display: flex;
  align-items: center;
  padding: 0 10px;
  margin-bottom: 10px;
}
</style>
